﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;

namespace _12306Bot
{
    public partial class FrmOrderPassCode : Form
    {
        /// <summary>登陆还是预订</summary>
        private char LoginOrBook;
        /// <summary>父窗体</summary>
        private FrmMain Opener;
        /// <summary>
        /// 是否响铃
        /// </summary>
        private Boolean IsBeep;

        public FrmOrderPassCode()
        {
            InitializeComponent();
        }

        public FrmOrderPassCode(FrmMain fmPara, char LoginOrBookPara)
            : this()
        {
            this.LoginOrBook = LoginOrBookPara;
            this.Opener = fmPara;
            if (LoginOrBookPara == 'L')
            {
                pbPassCode.Image = fmPara.pbLoginPassCode.Image;
                this.Text = "登录";
            }
            else
            {
                pbPassCode.Image = fmPara.pbOrderPassCode.Image;
                this.Text = "订票";
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (LoginOrBook == 'L')
            {
                Opener.txtLoginPassCode.Text = txtPassCode.Text;
            }
            else
            {
                Opener.txtOrderPassCode.Text = txtPassCode.Text;
            }
            IsBeep = false;
            this.Dispose();
        }

        private void pbPassCode_Click(object sender, EventArgs e)
        {
            Opener.getPassCode((new Random(DateTime.Now.Millisecond).NextDouble()).ToString(), LoginOrBook);
            if (LoginOrBook == 'L')
            {
                //克隆，否则会出现错误“对象当前正在其他地方使用”
                pbPassCode.Image = (Image)Opener.pbLoginPassCode.Image.Clone();
            }
            else
            {
                //克隆，否则会出现错误“对象当前正在其他地方使用”
                pbPassCode.Image = (Image)Opener.pbOrderPassCode.Image.Clone();
            }
        }

        private void FrmOrderPassCode_Load(object sender, EventArgs e)
        {
            if (LoginOrBook != 'L')
            {
                IsBeep = true;
                Thread td = new Thread(playBeep);
                td.Start();
            }
        }

        /// <summary>
        /// 播放音乐
        /// </summary>
        private void playBeep()
        {
            //设置线程为后台线程，以便在主线程退出时退出
            Thread.CurrentThread.IsBackground = true;

            while (IsBeep)
            {
                System.Media.SystemSounds.Beep.Play();
                Thread.Sleep(500);
            }
        }
    }
}
